package vip.lsjscl.flowboot.util.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisDistributedLockService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    public boolean tryLock(String key, long expire, TimeUnit timeUnit) {
        // 使用setIfAbsent实现原子性加锁
        Boolean success = redisTemplate.opsForValue().setIfAbsent(key, "locked", expire, timeUnit);
        return Boolean.TRUE.equals(success);
    }

    public void unlock(String key) {
        redisTemplate.delete(key);
    }
}